"""知识点列表相关视图

此模块包含用于展示知识点列表的视图函数和相关功能。
"""
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render, get_object_or_404
from core.models import Chapter, KnowledgePoint, TeacherSubjectAssignment


def _has_subject_permission(request: HttpRequest, subject_id: int) -> bool:
    """检查用户是否有权限操作指定学科

    Args:
        request: HTTP请求对象
        subject_id: 学科ID

    Returns:
        bool: 用户是否有权限
    """
    return TeacherSubjectAssignment.objects.filter(
        teacher=request.user,
        subject_id=subject_id
    ).exists()


@login_required
def knowledge_point_list(request: HttpRequest) -> HttpResponse:
    """知识点列表

    该视图函数展示指定章节的知识点列表，支持搜索功能。
    验证用户是否有权限操作指定章节所属的学科。

    Args:
        request: HTTP请求对象，包含章节ID和搜索关键词参数

    Returns:
        HttpResponse: 渲染的知识点列表页面
    """
    chapter_id = request.GET.get('chapter_id')
    search_query = request.GET.get('search', '')

    if not chapter_id:
        return render(request, 'knowledge_point/error.html', {
            'message': '章节ID不能为空'
        }, status=400)

    chapter = get_object_or_404(Chapter, id=chapter_id)

    # 验证用户是否有权限操作此章节所属的学科
    if not _has_subject_permission(request, chapter.subject_id):
        return render(request, 'knowledge_point/permission_denied.html', status=403)

    # 基本查询：获取指定章节的所有知识点
    knowledge_points = KnowledgePoint.objects.filter(chapter=chapter)

    # 如果有搜索关键词，添加搜索条件
    if search_query:
        knowledge_points = knowledge_points.filter(
            Q(name__icontains=search_query) |
            Q(description__icontains=search_query)
        )

    # 按创建时间降序排列
    knowledge_points = knowledge_points.order_by('-created_at')

    return render(request, 'knowledge_point/knowledge_point_list.html', {
        'knowledge_points': knowledge_points,
        'chapter': chapter,
        'search_query': search_query
    })